package com.gopay.webtest.controller.cloud;

import com.gopay.webtest.controller.base.BaseController;
import com.gopay.webtest.handler.cloud.TransCloudSignHandler;
import com.gopay.webtest.util.DateUtils;
import com.gopay.webtest.util.UploadFileUtil;
import com.gopay.webtest.vo.cloud.Cloud0621Vo;
import com.gopay.webtest.xml.XmlDao;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Johnson on 2017/1/4.
 */
@RequestMapping("/cloud/uploadCertController")
@Controller
public class CloudBackUploadController extends BaseController {

    private static final String BASE_URI = "/cloud/api/uploadCert/doUpload.shtml";

    @Resource(name = "xmlDao")
    private XmlDao xmlDao;

    @Resource(name="transCloudSignHandler")
    private TransCloudSignHandler transCloudSignHandler;

    @RequestMapping("/uploadApply")
    public ModelAndView uploadApply() {
        ModelAndView mv = new ModelAndView();
        try {
            Map<String, String> map = xmlDao.readData4Map("cloud_apply", "backUpload");
            map.put("reqTime", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
            mv = new ModelAndView("cloud.charge.uploadCertApply");
            mv.addObject("config", map);
            mv.addObject("remote_cloud_url",getBaseUrl());
        } catch (Exception e) {
            logger.error("跳转页面", e);
        }
        return mv;
    }

    /* @RequestMapping("/uploadApply")
    public ModelAndView uploadApply() {
        ModelAndView mv = new ModelAndView();
        try {
            Map<String, String> map = xmlDao.readData4Map("cloud_apply", "backUpload");
            map.put("reqTime", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
            mv = new ModelAndView("cloud.charge.uploadCertApply");
            mv.addObject("config", map);
        } catch (Exception e) {
            logger.error("跳转页面", e);
        }
        return mv;
    }*/

    @RequestMapping(value = "/doUpload",method = RequestMethod.POST)
    public void doUpload(DefaultMultipartHttpServletRequest request,@ModelAttribute Cloud0621Vo cloud0621Vo,HttpServletResponse response) {
        Map<String,Object> data = new HashMap<>();
        String result = "";
        try {
            //配合测试，增加otherFileType
            String otherFileType = request.getParameter("otherFileType");
            if(otherFileType != null && !"".equals(otherFileType)) {
                cloud0621Vo.setFileType(otherFileType);
            }
            // 签名
            transCloudSignHandler.sign(cloud0621Vo.getTranCode()+"_"+cloud0621Vo.getVersion(), "signType", "signValue", cloud0621Vo, getRequest());
            // 构建上送的参数信息
            data = buildReqData(cloud0621Vo);
            // 设置文件
            CommonsMultipartFile multipartFile = (CommonsMultipartFile) request.getFile("file");
            File file = null;
            if(multipartFile != null) {
                DiskFileItem fi = (DiskFileItem)multipartFile.getFileItem();
                file = fi.getStoreLocation();
            }
            data.put("file",file);
            String baseUrl = getBaseUrl();
            if(baseUrl != null) {
                logger.error("上传图片的地址为："+baseUrl);
                result = UploadFileUtil.uploadFile(data, getBaseUrl());
                logger.error("cloudat返回的数据："+result);
                response.setContentType("text/Xml;charset=UTF-8");
                response.getWriter().write(result);
            }
        } catch (Exception e) {
            logger.error("cloud back upload file error",e);
            String message = e.getMessage();
            if(message == null  || "".equals(message)) {
                message = "上传失败！";
            }
            response.setContentType("text/plain;charset=UTF-8");
            try {
                response.getWriter().write(message);
            } catch (IOException e1) {
                logger.error("cloud back upload file error",e1);
            }
        }
    }

    private Map<String,Object> buildReqData(Cloud0621Vo cloud0621Vo) {
        Map<String,Object> data = new HashMap<>();
        data.put("version",cloud0621Vo.getVersion());
        data.put("tranCode",cloud0621Vo.getTranCode());
        data.put("merchantID",cloud0621Vo.getMerchantID());
        data.put("agreeId",cloud0621Vo.getAgreeId());
        data.put("fileType",cloud0621Vo.getFileType());
        data.put("reqTime",cloud0621Vo.getReqTime());
        data.put("signType",cloud0621Vo.getSignType());
        data.put("signValue",cloud0621Vo.getSignValue());
        data.put("verficationCode",cloud0621Vo.getVerficationCode());
        return data;
    }

    private String getBaseUrl() {
        Map<String,String> devUrl = (Map<String, String>) getRequest().getSession().getAttribute("gopay_webtest_URL");
        String dom = devUrl.get("dom");
        String baseUrl = "";
        if(dom.contains("localhost")
                || dom.contains("127.0.0.1")
                || dom.contains("dev")
                || dom.contains("test")
                || dom.contains("bank")
                || dom.contains("gray")
                || dom.contains("mer")) {
           baseUrl = dom.replace("gateway","cloudat");
        } else if("http://www.gopay.com.cn".equals(dom)) {
            baseUrl = "http://cloudat.gopay.com.cn";
        } else if(dom.contains("gateway")) {
            baseUrl = dom.replace("gateway","cloudat");
        }
        if(!"".equals(baseUrl)) {
            return baseUrl+BASE_URI;
        }
        return null;
    }
}
